import { ContainerHost } from "../../Container";
import { GroupManService } from "../GroupManService";
import { HoverFilter } from "./HoverFilter";

export class HighlightTool implements Sippreep.Viewing.ToolInterface {

    private active: boolean = false;
    private oldHoverData?: Record<string, any> = {};
    private hoverData: Record<string, any> = {};
    filter: HoverFilter;

    constructor(private viewer: Sippreep.Viewing.Viewer3D) {
        this.filter = new HoverFilter();
    }

    isActive(): boolean {
        return this.active;
    }
    getName(): string {
        return HighlightTool.name;
    }
    getNames(): string[] {
        return [HighlightTool.name];
    }
    register(): void {

    }
    deregister(): void {

    }
    activate(name: string, viewerApi?: Sippreep.Viewing.Viewer3D): void {
        this.active = true;
        this.viewer.disableHighlight(true);
    }
    deactivate(name: string): void {
        this.active = false;
        this.viewer.disableHighlight(false);
    }
    update(): boolean {
        // 取消先前鼠标指到的构件的高亮
        if (this.oldHoverData && this.oldHoverData.clientX && (this.hoverData?.modelName !== this.oldHoverData.modelName || this.hoverData?.dbid !== this.oldHoverData.dbid)) {
            //@ts-ignore
            this.viewer.impl.clearHighlight();
            this.oldHoverData = {};
        }
        // 高亮当前鼠标指到的构件
        //@ts-ignore
        if (this.hoverData && this.hoverData.clientX && this.hoverData.clientY) {
            if (this.filter.judgeFailed(this.hoverData.modelName, this.hoverData.dbid)) {
                return false;
            }
            //@ts-ignore
            this.viewer.impl.rolloverObjectViewport(this.viewer.impl.clientToViewport(this.hoverData.clientX, this.hoverData.clientY));
            Object.assign(this.oldHoverData, this.hoverData);
        }
        return false;
    }
    handleMouseMove(event: MouseEvent): boolean {
        //@ts-ignore
        const result = this.viewer.impl.hitTest(event.canvasX, event.canvasY, true);
        // console.log(result);
        if (result) {
            const model = result.model;
            const dbId = result.dbId;
            //@ts-ignore
            this.hoverData = { modelName: ContainerHost.Current.Get(GroupManService).getModelName(model), dbid: dbId, clientX: event.clientX, clientY: event.clientY };
        } else {
            this.hoverData = {};
        }
        return false;
    }

}